﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.Configuration;
using Librerias;
using Resources;

namespace Aplicacion
{

    ///<summary>
    ///</summary>
    public partial class Default : System.Web.UI.Page
    {
        


        private const string PassPhrase = "Pas5pr@se";
        private const string SaltValue = "s@1tValue";
        private const string HashAlgorithm = "SHA1";
        private const int PasswordIterations = 2;
        private const string InitVector = "@1B2c3D4e5F6g7H8";
        private const int KeySize = 256;

        private static readonly string _rutaAd = Configuracion.Get("rutaAD");
        private readonly string _userAd = Configuracion.Get("userAD");
        private readonly string _passAd = Encriptador.Decrypt(Configuracion.Get("passAD"), PassPhrase,
                                            SaltValue,
                                            HashAlgorithm,
                                            PasswordIterations,
                                            InitVector,
                                            KeySize);

        protected void Page_Load(object sender, EventArgs e)
        {

            //ObjetoAd _ob = new ObjetoAd("pcarioca", "Tdf999gob");
            //bool asd = _ob.CrearHome();
                

        }

        private bool Authenticate(string user, string pass)
        {
            var authentic = false;
            try
            {
                new DirectoryEntry(_rutaAd, user, pass);
                authentic = true;
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
         //   Label1.Text = "Login Correcto";
            return authentic;

        }

        private static DirectoryEntry GetDirectoryObject(string user, string pass)
        {
            var oDe = new DirectoryEntry(_rutaAd, user, pass, AuthenticationTypes.Secure);
            return oDe;
        }

        private DirectoryEntry GetUser(string userName, string pass)
        {
            try
            {
                var de = GetDirectoryObject(userName, pass);
                var deSearch = new DirectorySearcher
                                   {
                                       SearchRoot = de,
                                       Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))",
                                       SearchScope = SearchScope.Subtree
                                   };

                SearchResult results = deSearch.FindOne();

                if (results != null)
                {

                    de = new DirectoryEntry(results.Path, _userAd, _passAd, AuthenticationTypes.Secure);
                        foreach (string path in de.Properties["memberOf"]) 
                            Console.WriteLine(path);


                    return de;
                }
                return null;
            }
            catch (Exception ex)
            {
                lblError.ForeColor = System.Drawing.Color.Red;
                lblError.Text = ex.Message;
            }

            return null;
        }

        ///<summary>
        ///</summary>
        ///<param name="user"></param>
        ///<param name="pass"></param>
        ///<returns></returns>
        public bool SetPassword(DirectoryEntry user, string pass)
        {
            try
            {
                user.Invoke("setPassword", new object[] {pass });
                user.CommitChanges();
                return true;
            }
            catch (Exception ex)
            {
 
                lblError.ForeColor = System.Drawing.Color.Red;
                //lblError.Text = "La contraseña debe tener por lo menos una letra mayuscula, numeros y tener mas de 8 caracteres";
                if (lblError.Text == "")
                    lblError.Text = NC_ADmin.PasswordNoCumpleRequisitos;


                return false;
            }


        }

        protected void BtnEnviarClick(object sender, EventArgs e)
        {
           
            //var de = GetUser(txtUsuario.Text.Trim(), txtPasswordActual.Text.Trim());
            using (var objeto = new ObjetoAd(txtUsuario.Text.Trim(), txtPasswordActual.Text.Trim()))
            {
                //if (objeto.DirectoryEntry == null) return;
                try
                {
                    objeto.UserPassword = txtPasswordNuevo.Text.Trim();
                    objeto.Guardar();


                    txtUsuario.Text = String.Empty;
                    Notificaciones.Correcto(NC_ADmin.PasswordCambiado);
                }
                catch (NullReferenceException ex)
                {
                    Notificaciones.Error("El usuario y/o la contraseña actual son incorrectos");
                }
                catch (Exception ex)
                {
                    Notificaciones.Error(ex.Message);
                }
                finally
                {
                    txtUsuario.Text = String.Empty;
                }
                
            }

            //if (!SetPassword(de, txtPasswordNuevo.Text.Trim())) return;
            //if (!Authenticate(txtUsuario.Text.Trim(), txtPasswordNuevo.Text.Trim())) return;
            
        }
        protected String getReferrer()
        {
            if (Request.UrlReferrer != null)
            {
                return Request.UrlReferrer.ToString();
            }
            else
            {
                return "javascript:history.back(1)";
            }
            
        }
    }

 
}
